<?php
namespace App\Logics;
use App\Models\BrandModel;
use App\Models\CategoryModel;
use App\Models\ChannelModel;
use App\Models\GoodsLeaseModel;
use App\Models\GoodsLeaseTermModel;
use App\Models\GoodsModel;
use App\Models\GoodsSkuModel;
use App\Models\GoodsImgModel;
use App\Models\AttrSpecModel;
use App\Models\AttrTypeModel;
use App\Models\AttrValModel;
use App\Models\SupplierModel;
use App\Models\ChannelCateGoodsModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

//逻辑处理
class GoodsLogic extends BaseLogic{


    public function __construct( )
    {

    }

    /**
     * @return array
     */
    public function getGoodsAdd(){
        $category = CategoryLogic::getCategory();
        $brand = BrandLogic::getBrand();
        $supplier = SupplierLogic::getSupplier();
        $category = $this->tree($category);
        $data = [
            'brand' => $brand,
            'supplier' => $supplier,
            'category' => $category
        ];
        return $data;
    }

    /**商品添加
     * @param array $para
     * @return array
     */
    public   function goodsAdd(array $para){
        $supplier_id = isset($para['supplier_id'])?$para['supplier_id']:0;
        $brand_id = isset($para['brand_id'])?$para['brand_id']:0;
        $cate_id = isset($para['cate_id'])?$para['cate_id']:0;
        $goods_name = isset($para['goods_name'])?$para['goods_name']:0;
        $keyword = isset($para['keyword'])?$para['keyword']:0;
        $detail = isset($para['detail'])?$para['detail']:0;
        $goods_sale_phone = isset($para['goods_sale_phone'])?$para['goods_sale_phone']:0;
        $goods_price = isset($para['goods_price'])?$para['goods_price']:0;
        $goods_official_price = isset($para['goods_official_price'])?$para['goods_official_price']:0;
        $goods_purchase_price = isset($para['goods_purchase_price'])?$para['goods_purchase_price']:0;
        $is_required = isset($para['is_required'])?$para['is_required']:0;
        $goods_installation_charge = isset($para['goods_installation_charge'])?$para['goods_installation_charge']:0;
        $goods_installation_show = isset($para['goods_installation_show'])?$para['goods_installation_show']:'';
        $is_required_insurance = isset($para['is_required_insurance'])?$para['is_required_insurance']:0;
        $goods_insurance = isset($para['goods_insurance'])?$para['goods_insurance']:'';
        $goods_tenancy_term = isset($para['goods_tenancy_term'])?$para['goods_tenancy_term']:[];

        if (empty($supplier_id)) return json_success('请选择供货商');
        if (!SupplierLogic::isOne($supplier_id)) return json_error('该供货商不存在');
        if (empty($brand_id)) return json_error('请选品牌');
        if (!BrandLogic::isOne($brand_id)) return json_error('该品牌不存在');
        if (empty($cate_id)) return json_error('请选择分类');
        if (!CategoryLogic::isOne($cate_id)) return json_error('该分类不存在');

        if (empty($goods_name)) return error('请填写商品名称');
        if (empty($keyword)) return error('请填写商品关键词');
        if (empty($goods_sale_phone)) return error('请填写商品售后电话');
        if (empty($goods_price)) return error('请填写商品价格');
        if ($goods_price < 0) return error('商品价格不能为负数');
        if (empty($goods_official_price)) return error('请填写商品官方价格');
        if ($goods_official_price < 0) return error('商品官方价格不能为负数');
        if (empty($goods_purchase_price)) return error('请填写商品进货价');
        if ($goods_purchase_price < 0) return error('商品进货价不能为负数');
        if ($goods_purchase_price > $goods_price) return error('商品价格必须大于进货价');
        if ($goods_installation_charge < 0) return error('配件费用不能为负数');
        if ($goods_insurance < 0) return error('意外保障费用不能为负数');

        $supplier = SupplierLogic::getOne($supplier_id);
        $category = CategoryLogic::getOne($cate_id, ['cate_code']);


        $data = [
            'supplier_id' => $supplier_id,
            'supplier_name' => $supplier['name'] ?? '',
            'brand_id' => $brand_id,
            'cate_id' => $cate_id,
            'cate_code' => $category['cate_code'] ?? '',
            'goods_name' => $goods_name,
            'keyword' => $keyword,
            'detail' => $detail,
            'goods_sale_phone' => $goods_sale_phone,
            'goods_price' => number_deal($goods_price, 2),
            'goods_official_price' => number_deal($goods_official_price, 2),
            'goods_purchase_price' => number_deal($goods_purchase_price, 2),
            'is_required' => $is_required == 1 ? 1 : 2,
            'goods_installation_charge' => number_deal($goods_installation_charge, 2),
            'goods_installation_show' => $goods_installation_show,
            'is_required_insurance' => $is_required_insurance == 1 ? 1 : 2,
            'goods_insurance' => number_deal($goods_insurance, 2),
            'is_putaway' => 1,
            'is_delete' => 0,
            'create_time' => time(),
        ];
        if($goods_tenancy_term && is_array($goods_tenancy_term)){
            $goods_tenancy_term=array_map(function($v){
                return (int)$v;
            },$goods_tenancy_term);
            $goods_tenancy_term=array_unique($goods_tenancy_term);
            rsort($goods_tenancy_term);
            $data['goods_tenancy_term']=join(',',$goods_tenancy_term);
            $data['monthly_rent']= number_deal($data['goods_price']/$goods_tenancy_term[0],2);
        }

        $goods_id = GoodsModel::insertGetId($data);
        if ($goods_id) return success('添加成功', ['goods_id' => $goods_id]);
        return error('添加失败');
    }

    /**
     * @param int $goods_id
     * @return array
     */
    public function getGoodsEdit(int $goods_id){
        $goods = GoodsLogic::getOne($goods_id);
        $category = CategoryLogic::getCategory();
        $brand = BrandLogic::getBrand();
        $supplier = SupplierLogic::getSupplier();
        $category = $this->tree($category);

        $goods['goods_tenancy_term']=$goods['goods_tenancy_term']?explode(',',$goods['goods_tenancy_term']):[];
        return [
            'brand' => $brand,
            'supplier' => $supplier,
            'category' => $category,
            'goods' => $goods
        ];
    }

    public  function goodsEdit(array $para){
        $supplier_id = isset($para['supplier_id'])?$para['supplier_id']:0;
        $brand_id = isset($para['brand_id'])?$para['brand_id']:0;
        $cate_id = isset($para['cate_id'])?$para['cate_id']:0;
        $goods_name = isset($para['goods_name'])?$para['goods_name']:0;
        $keyword = isset($para['keyword'])?$para['keyword']:0;
        $detail = isset($para['detail'])?$para['detail']:0;
        $goods_sale_phone = isset($para['goods_sale_phone'])?$para['goods_sale_phone']:0;
        $goods_price = isset($para['goods_price'])?$para['goods_price']:0;
        $goods_official_price = isset($para['goods_official_price'])?$para['goods_official_price']:0;
        $goods_purchase_price = isset($para['goods_purchase_price'])?$para['goods_purchase_price']:0;
        $is_required = isset($para['is_required'])?$para['is_required']:0;
        $goods_installation_charge = isset($para['goods_installation_charge'])?$para['goods_installation_charge']:0;
        $goods_installation_show = isset($para['goods_installation_show'])?$para['goods_installation_show']:'';
        $is_required_insurance = isset($para['is_required_insurance'])?$para['is_required_insurance']:0;
        $goods_insurance = isset($para['goods_insurance'])?$para['goods_insurance']:'';
        $goods_id = isset($para['goods_id'])?$para['goods_id']:0;
        $goods_tenancy_term = isset($para['goods_tenancy_term'])?$para['goods_tenancy_term']:[];

        $goods = GoodsLogic::getOne($goods_id, ['is_putaway']);
        if (empty($goods)) return error('该商品不存在');
        if ($goods['is_putaway'] == 3) return error('商品已上线不能被编辑');
        if (empty($supplier_id)) return error('请选择供货商');
        if (!SupplierLogic::isOne($supplier_id)) return error('该供货商不存在');
        if (empty($brand_id)) return json_error('请选品牌');
        if (!BrandLogic::isOne($brand_id)) return error('该品牌不存在');
        if (empty($cate_id)) return error('请选择分类');
        if (!CategoryLogic::isOne($cate_id)) return error('该分类不存在');

        if (empty($goods_name)) return error('请填写商品名称');
        if (empty($keyword)) return error('请填写商品关键词');
        if (empty($goods_sale_phone)) return error('请填写商品售后电话');
        if (empty($goods_price)) return error('请填写商品价格');
        if ($goods_price < 0) return error('商品价格不能为负数');
        if (empty($goods_official_price)) return error('请填写商品官方价格');
        if ($goods_official_price < 0) return error('商品官方价格不能为负数');
        if (empty($goods_purchase_price)) return error('请填写商品进货价');
        if ($goods_purchase_price < 0) return error('商品进货价不能为负数');
        if ($goods_purchase_price > $goods_price) return error('商品价格必须大于进货价');
        if ($goods_installation_charge < 0) return error('配件费用不能为负数');
        if ($goods_insurance < 0) return error('意外保障费用不能为负数');

        $supplier = SupplierLogic::getOne($supplier_id);
        $category = CategoryLogic::getOne($cate_id, ['cate_code']);

        $data = [
            'supplier_id' => $supplier_id,
            'supplier_name' => $supplier['name'] ?? '',
            'brand_id' => $brand_id,
            'cate_id' => $cate_id,
            'cate_code' => $category['cate_code'] ?? '',
            'goods_name' => $goods_name,
            'keyword' => $keyword,
            'detail' => $detail,
            'goods_sale_phone' => $goods_sale_phone,
            'goods_price' => number_deal($goods_price, 2),
            'goods_official_price' => number_deal($goods_official_price, 2),
            'goods_purchase_price' => number_deal($goods_purchase_price, 2),
            'is_required' => $is_required == 1 ? 1 : 2,
            'goods_installation_charge' => number_deal($goods_installation_charge, 2),
            'goods_installation_show' => $goods_installation_show,
            'is_required_insurance' => $is_required_insurance == 1 ? 1 : 2,
            'goods_insurance' => number_deal($goods_insurance, 2),
        ];
        if($goods_tenancy_term && is_array($goods_tenancy_term)){
            $goods_tenancy_term=array_map(function($v){
                return (int)$v;
            },$goods_tenancy_term);
            $goods_tenancy_term=array_unique($goods_tenancy_term);
            rsort($goods_tenancy_term);
            $data['goods_tenancy_term']=join(',',$goods_tenancy_term);
            $data['monthly_rent']= number_deal($data['goods_price']/$goods_tenancy_term[0],2);
        }

        $res = GoodsModel::where('goods_id', $goods_id)->update($data);
        if ($res) return success('编辑成功');
        return error('编辑失败');
    }

    /**
     * @param int $goods_id
     * @return array|string
     */
    public function getGoodsAddImg(int $goods_id){
        $fields = ['goods_img_list', 'goods_order_thumbnail', 'goods_id'];
        $goods = GoodsLogic::getOne($goods_id, $fields);
        if (empty($goods)) {
            return '参数错误';
        }
        $img = GoodsImgLogic::getListByGoodsId($goods_id);
        $url = config('sys.img_url');
        return ['goods' => $goods, 'img' => $img, 'url' => $url . '/'];
    }
    public  function goodsAddImg(Request $request,array $para){
        $goods_id = isset($para['goods_id'])? $para['goods_id']:0;
        $id = isset($para['id'])? $para['id']:0;
        $type = isset($para['type'])? $para['type']:'';
        $action = isset($para['action'])? $para['action']:'';
        $img_type = isset($para['img_type'])? $para['img_type']:1;

        $goods = GoodsLogic::getOne($goods_id, ['goods_img_list', 'goods_order_thumbnail', 'goods_id']);
        if (empty($goods)) {
            return error('该商品不存在');
        }
        if ($action == 'update') {
            $data = $this->uploadImg($request, 'img', 'goods');
            if ($data['status'] == 0) {
                return error($data['data']);
            }
            if ($id == 0) {
                if (!in_array($type, ['goods_img_list', 'goods_order_thumbnail'])) {
                    $this->deleteImg($data['data']);
                    return error('参数有误');
                }

                $res = GoodsModel::where('goods_id', $goods_id)->update([$type => $data['data']]);
                if (empty($res)) {
                    $this->deleteImg($data['data']);
                    return error('图片更新失败');
                }
                $url = config('sys.img_url') . '/' . $data['data'];
                if ($goods[$type]) {
                    $this->deleteImg($goods[$type]);
                }
                return success('更新成功', ['url' => $url]);

            }
            if ($id > 0) {
                $img = GoodsImgLogic::getOne($id);
                if (empty($img)) {
                    $this->deleteImg($data['data']);
                    return error('参数有误');
                }
                $res = GoodsImgModel::where('img_id', $id)->update(['img_src' => $data['data']]);
                if (empty($res)) {
                    $this->deleteImg($data['data']);
                    return error('图片更新失败');
                }
                $url = config('sys.img_url') . '/' . $data['data'];
                if ($img['img_src']) {
                    $this->deleteImg($img['img_src']);
                }
                return success('更新成功', ['url' => $url]);
            }
        }
        if ($action == 'add') {
            $data = $this->uploadImg($request, 'img', 'goods');
            if ($data['status'] == 0) {
                return error($data['data']);
            }
            $img_type = $img_type == 1 ? 1 : 2;
            $res = GoodsImgModel::insert(['goods_id' => $goods_id, 'img_src' => $data['data'], 'img_type' => $img_type]);
            if ($res) return success('添加成功');
            return error('添加失败');
        }
        return error('参数错误');
    }

    public   function getCategory(int $cha_id){
        $res = ChannelLogic::isOne($cha_id);
        if (empty($res)) return error('渠道不合法');
        $data = CategoryLogic::getListByChaId($cha_id);
        if (empty($data)) {
            return error('无分类');
        }
        $pid_ar = array_unique(array_column($data, 'pid'));
        foreach ($data as $k => $v) {
            if (in_array($v['cate_id'], $pid_ar)) {
                $data[$k]['is_son'] = 0;
            } else {
                $data[$k]['is_son'] = 1;
            }
        }

        $data = $this->tree($data);
        $html = "";
        foreach ($data as $k => $v) {
            if ($v['is_son'] == 0) {
                $html .= '<option value="' . $v['cate_id'] . '" disabled="disabled"  >' . $v['level_str'] . $v['cate_name'] . '</option>';
            } else {
                $html .= '<option value="' . $v['cate_id'] . '"   >' . $v['level_str'] . $v['cate_name'] . '</option>';
            }
        }
        return success('ok', ['html' => $html]);
    }

    public  function batchDeal(string $ids,string $type){
        $type_ar = ['delete', 'refuse', 'down', 'submit'];
        if (empty($ids) || !in_array($type, $type_ar)) {
            return error('参数有误');
        }
        $ids_ar = explode(',', trim($ids, ','));
        $ids_ar = array_map(function ($v) {
            return (int)$v;
        }, $ids_ar);
        $res = '';
        if ($type == 'delete') {//软删除
            $res = GoodsModel::whereIn('goods_id', $ids_ar)->update(['is_delete' => 1]);
        }
        if ($type == 'refuse') { //驳回
            $res = GoodsModel::whereIn('goods_id', $ids_ar)->whereRaw("is_putaway in (2,5)")->update(['is_putaway' => 5, 'is_delete' => 0]);
        }
        if ($type == 'down') { //下架
            $res = GoodsModel::whereIn('goods_id', $ids_ar)->whereRaw("is_putaway=3")->update(['is_putaway' => 4, 'is_delete' => 0]);
        }
        if ($type == 'submit') { //提交审核
            $res = GoodsModel::whereIn('goods_id', $ids_ar)->whereRaw("is_putaway in(1,5)")->update(['is_putaway' => 2, 'is_delete' => 0]);
        }

        if (empty($res)) return error('执行失败');
        return success('执行成功');
    }

    /** 删除
     * @param int $goods_id
     * @return array
     */
    public function ajaxDel(int $goods_id){
        $data = GoodsModel::where('goods_id', $goods_id)->select('is_delete')->first();
        if (empty($data)) return error('参数错误');
        $data = ob_to_array($data);
        $is_delete = $data['is_delete'] == 1 ? 0 : 1;

        $res = GoodsModel::where('goods_id', $goods_id)->update(['is_delete' => $is_delete]);
        if (empty($res)) {
            return error('执行失败');
        }
        return success('ok', ['is_delete' => $is_delete]);
    }

    /** 渠道信息
     * @param int $goods_id
     * @return array
     */
    public  function goodsChannelInfo(int $goods_id){
        $data = ChannelCateGoodsLogic::getListByGoodsId($goods_id);
        if (empty($data)) return error('无数据');
        $cha_ids = array_column($data, 'cha_id');
        $cate_ids = array_column($data, 'cate_id');
        $channel = ChannelModel::whereIn('cha_id', $cha_ids)->where('cha_status', 2)->pluck("cha_describe", "cha_id");
        $category = CategoryModel::whereIn("cate_id", $cate_ids)->whereRaw("is_del=0 and is_hidden=2")->pluck('cate_name', 'cate_id');

        $channel = ob_to_array($channel);
        $category = ob_to_array($category);

        $cha_id_ar = array_keys($channel);
        $cate_id_ar = array_keys($category);
        $zhuijia_id = $zhuijia_name = [];
        foreach ($data as $k => $v) {
            if (!in_array($v['cha_id'], $cha_id_ar)) {
                continue;
            }
            if ($v['cate_id'] > 0 && !in_array($v['cate_id'], $cate_id_ar)) {
                continue;
            }
            $zhuijia_id[$v['cha_id']] = $v['cha_id'] . '=' . $v['cate_id'];
            $cate_str = $v['cate_id'] > 0 ? '&nbsp;&nbsp;&nbsp;&nbsp;' . $category[$v['cate_id']] : '';
            $zhuijia_name[$v['cha_id']] = $channel[$v['cha_id']] . $cate_str;
        }
        return success('ok', ['zhuijia_name' => $zhuijia_name, 'zhuijia_id' => $zhuijia_id]);
    }

    //添加数据
    public static function add(array $data){
        $ob=new GoodsModel();
        foreach($data as $k=>$v){
            $ob->$k=$v;
        }
       return  $ob->save();
    }

    //获取一条数据
    public static function getOne($goods_id,array $fields=['*']){
        $goods_id=(int)$goods_id;

        $data=GoodsModel::where('goods_id',$goods_id)->select($fields)->first();
        return ob_to_array($data);
    }

    //判断该数据是否存在
    public static function isOne($id){
        $id=(int)$id;
        return GoodsModel::where('goods_id',$id)->count();
    }

    /**
     * @param int $goods_id
     * attr_val的id为key,对应其类型及值
     */
    public static function getAttrValToTypeByGoodsId(int $goods_id){
        $attr_val=AttrValLogic::getAttrValByGoodsId($goods_id);
        $attr_vals=[];
        foreach($attr_val as $v){
            $attr_vals[$v['id']]=$v['attr_type'].':'.$v['attr_name'];
        }
        return $attr_vals;
    }

    /**获取商品租期
     * @param int $goods_id
     * @return array
     */
    public static function goodsLease(int $goods_id){
        $fileds=['goods_id','goods_price','goods_name'];
        $goods=GoodsLogic::getOne($goods_id,$fileds);
        if(empty($goods)) return '该商品不存在';

        $goods_lease=GoodsLeaseModel::where('goods_id',$goods_id)->get();
        $goods_lease=ob_to_array($goods_lease);
        $sku=array_column($goods_lease,'goods_sku_id')?:[0];

        $goods_sku= GoodsSkuModel::where("goods_id",$goods_id)
            ->whereIn('id',$sku)->select('id','goods_id','sku')->get();
        $goods_sku=ob_to_array($goods_sku);



        $attr_val=AttrValLogic::getAttrValByGoodsId($goods_id);
        $attr_val=ob_to_array($attr_val);
        $attr_vals=[];
        foreach($attr_val as $v){
            $attr_vals[$v['id']]=$v['attr_type'].':'.$v['attr_name'];
        }

        $goods_skus=[];
        foreach($goods_sku as $k=>$v){
            $goods_skus[$v['id']]='';
            if(empty($v['sku'])) continue;
            $ar=explode(',',$v['sku']);
            $ars=[];
            foreach($ar as $vv){
                $ars[]=isset($attr_vals[$vv])?$attr_vals[$vv]:'';
            }
            $goods_skus[$v['id']]=join(" | ",$ars);
        }

        $ids=array_column($goods_lease,'id');
        $term=GoodsLeaseTermModel::whereIn('goods_lease_id',$ids)->get();
        $term=ob_to_array($term);
        $terms=[];
        foreach($term as $v){
            $terms[$v['goods_lease_id']][]=$v;
        }

        foreach($goods_lease as $k=>$v){
            $goods_lease[$k]['sku_str']=isset($goods_skus[$v['goods_sku_id']])?$goods_skus[$v['goods_sku_id']]:'';
            $goods_lease[$k]['term']=isset($terms[$v['id']])?$terms[$v['id']]:[];
        }

        return [
            'goods'=>$goods,
            'list'=>$goods_lease
        ];
    }


    /** 上架
     * @param $goods_ids
     * @param $chastr
     * @return array
     * @throws \Exception
     */
    public  function shangjia($goods_ids,$chastr){
        $goods_ids=explode(',',trim($goods_ids,','));
        $cha_ar=explode(',',trim($chastr,','));
        if(empty($goods_ids) || empty($cha_ar)) return error('参数有误');

        $data=[];
        foreach($goods_ids as $k=>$v){
            foreach($cha_ar as $kk=>$vv){
                $ar=explode('=',$vv);
                $data[]=[
                    'goods_id'=>(int)$v,
                    'cha_id'=>!empty($ar[0])?(int)$ar[0]:0,
                    'cate_id'=>!empty($ar[1])?(int)$ar[1]:0
                ];
            }
        }


        foreach($data as $k=>$v){
            if($v['goods_id']<1 || $v['cha_id']<1)unset($data[$k]);
            $goods=GoodsLogic::getOne($v['goods_id'],['is_putaway']);
            if(empty($goods)){
                unset($data[$k]);continue;
            }

            //商品必须是待审核，或下降商品才能上架
            if(!in_array($goods['is_putaway'],[2,4])) {
                unset($data[$k]);continue;
            }
            $res=ChannelLogic::getOne($v['cha_id']);
            if(empty($res)){
                unset($data[$k]);continue;
            }

            $data[$k]['cha_cate_name']=$res['cha_describe'];
            $data[$k]['cate_code']=$res['cate_code'];
            $res= CategoryModel::select("cate_id")->whereRaw("is_del=0 and is_hidden=2 and cha_id=".$v['cha_id'])->first();
            if($res && $v['cate_id']==0){
                return error('有渠道未选择分类');
            }
            if($v['cate_id']>0){
                $res=CategoryModel::select('cate_id','cate_code','cate_name')
                    ->whereRaw("cate_id=".$v['cate_id']." and is_del=0 and is_hidden=2 and cha_id=".$v['cha_id'])->first();
                if(empty($res)){
                    unset($data[$k]);continue;
                }
                $res=ob_to_array($res);
                $data[$k]['cha_cate_name'].='-'.$res['cate_name'];
                $data[$k]['cate_code']=$res['cate_code'];
            }
        }
        if(!$data) return error('参数有误1');


        DB::beginTransaction();
        try{
            $ids=array_column($data,'goods_id');
            ChannelCateGoodsModel::whereIn('goods_id',$ids)->delete();
            $res=ChannelCateGoodsModel::insert($data);
            GoodsModel::whereIn('goods_id',$ids)->update(['is_putaway'=>3,'is_delete'=>0]);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return error($e->getMessage());
        }
        return success('上架成功');
    }

    /** 商品所有信息
     * @param int $goods_id
     * @return array
     */
    public  function goodsShow(int $goods_id){
        if(empty($goods_id)) return '缺少参数';
        $goods=GoodsLogic::getOne($goods_id);
        if(empty($goods)) return '该商品不存在';
        $category=CategoryLogic::getOne($goods['cate_id'],['cate_name']);
        $brand=BrandLogic::getOne($goods['brand_id'],['brand_name']);
        $supplier=SupplierLogic::getOne($goods['supplier_id'],['name']);
        $attr=AttrSpecLogic::getListByGoodsId($goods_id);

        $attr_type=AttrTypeLogic::getListByGoodsId($goods_id);

        $attr_ids = array_column($attr_type, 'attr_id') ?: [0];
        $attr_val=AttrValLogic::getListByAttrIds($attr_ids);
        $attr_vals=[];
        $zhi_name=[];
        foreach($attr_val as $v){
            $attr_vals[$v['attr_id']][]=$v;
            $zhi_name[$v['id']]=$v;
        }
        $attr_types=[];
        foreach ($attr_type as $k=>$v) {
            $attr_type[$k]['zhi']=$attr_vals[$v['attr_id']]??[];
            $attr_types[$v['attr_id']]=$v;
        }
        foreach($zhi_name as $k=>$v){
            $zhi_name[$k]['attr_type']=isset($attr_types[$v['attr_id']])?$attr_types[$v['attr_id']]['attr_type']:'';
        }

        $goods_sku=GoodsSkuLogic::getListByGoodsId($goods_id);
        $goods_skus=[];
        foreach($goods_sku as $k=>$v){
            $sku=explode(',',trim($v['sku'],','));
            $str='';
            foreach($sku as $v1){
                $str.=isset($zhi_name[$v1])?$zhi_name[$v1]['attr_type'].':'.$zhi_name[$v1]['attr_name'].' | ':'';
            }
            $goods_sku[$k]['sku_str']=trim($str,' | ');
            $goods_sku[$k]['goods_name']=$goods['goods_name'];
            $goods_skus[$v['id']]=$goods_sku[$k];
        }

        $goods_lease=GoodsLeaseLogic::getListByGoodsId($goods_id);
        $ids=array_column($goods_lease,'id');
        $term=GoodsLeaseTermLogic::getListByGoodsLeaseIds($ids);
        $terms=[];
        foreach($term as $v){
            $terms[$v['goods_lease_id']][]=$v;
        }
        foreach($goods_lease as $k=>$v){
            $goods_lease[$k]['sku_str']='';
            if($v['goods_sku_id']){
                $goods_lease[$k]['sku_str']=isset($goods_skus[$v['goods_sku_id']])?$goods_skus[$v['goods_sku_id']]['sku_str']:'';
            }
            $goods_lease[$k]['term']=isset($terms[$v['id']])?$terms[$v['id']]:[];
        }

        $img=GoodsImgLogic::getListByGoodsId($goods_id);

        $url=config('sys.img_url').'/';
        $data=[
            'brand'=>$brand,
            'supplier'=>$supplier,
            'category'=>$category,
            'goods'=>$goods,
            'attr'=>$attr,
            'sku'=>$attr_type,
            'url'=>$url,
            'goods_sku'=>$goods_sku,
            'goods_lease'=>$goods_lease,
            'img'=>$img
        ];
        return $data;
    }


    /** 商品删除
     * @param int $goods_id
     * @return array
     */
    public function delete(int $goods_id){
        $goods_id = (int)request('goods_id');
        $res = GoodsModel::where('goods_id', $goods_id)->update(['is_delete' => 1]);

        if ($res) {
            return success('删除成功');
        }
        return error('删除失败');
    }

    /** 删除一组sku
     * @param int $id
     * @return array
     * @throws \Exception
     */
    public  function goodsSkuDelete(int $id){
        $sku=GoodsSkuLogic::getOne($id,['goods_id']);
        if(empty($sku)) return error('参数错误');
        $sku=ob_to_array($sku);
        $goods_id=$sku['goods_id'];

        //删除一组sku,同时也要删除对应的租期
        DB::beginTransaction();
        try{
            $res=GoodsSkuModel::where('id',$id)->delete();
            if(empty($res))  throw new \Exception('删除失败');
            $ar=GoodsLeaseModel::where([['goods_id',$goods_id],['goods_sku_id',$id]])->pluck('id');
            $ar=ob_to_array($ar);
            if($ar){
                GoodsLeaseTermModel::whereIn('goods_lease_id',$ar)->delete();
                $res= GoodsLeaseModel::where([['goods_id',$goods_id],['goods_sku_id',$id]])->delete();
                if(empty($res))  throw new \Exception('删除失败');
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return error($e->getMessage());
        }

        return success('删除成功');
    }

    /** 获取商品sku
     * @param int $goods_id
     * @return array|\Illuminate\Support\Collection|mixed|string
     */
    public  function goodsSku(int $goods_id){
        $goods = GoodsLogic::getOne($goods_id, ['goods_name', 'goods_id','goods_price','goods_official_price','goods_purchase_price']);
        if (empty($goods)) return '参数错误';
        $data=AttrValLogic::getAttrValByGoodsId($goods_id);
        $attr_types = [];
        $zhi_names = [];
        foreach ($data as $k => $v) {
            $attr_types[$v['attr_id']]['zhi'][] = ['id' => $v['id'], 'attr_name' => $v['attr_name']];
            $attr_types[$v['attr_id']]['attr_type'] = $v['attr_type'];
            $zhi_names[$v['id']] = ['attr_type' => $v['attr_type'], 'attr_name' => $v['attr_name'], 'attr_id' => $v['attr_id']];
        }

        $goods_sku = GoodsSkuLogic::getListByGoodsId($goods_id);
        foreach ($goods_sku as $k => $v) {
            $sku = explode(',', trim($v['sku'], ','));
            $str = '';
            foreach ($sku as $v1) {
                $str .= isset($zhi_names[$v1]) ? $zhi_names[$v1]['attr_type'] . ':' . $zhi_names[$v1]['attr_name'] . ' | ' : '';
            }
            $goods_sku[$k]['sku_str'] = trim($str, ' | ');
            $goods_sku[$k]['goods_name'] = $goods['goods_name'];
        }

        $data = [
            'goods_sku' => $goods_sku,
            'goods' => $goods,
            'attr_type' => $attr_types,
            'zhi_name' => $zhi_names
        ];
        return $data;

    }

    //删除商品图片
    public function goodsDeleteImg(Request $request,int $goods_id,int $id,$type)
    {
            $goods_id = (int)request('goods_id');
            $id = (int)request('id');
            $type = trim(request('type'));
            $goods = GoodsLogic::getOne($goods_id, ['goods_img_list', 'goods_order_thumbnail', 'goods_id']);
            if (empty($goods)) {
                return error('该商品不存在');
            }
            if ($id == 0) {
                if (!in_array($type, ['goods_img_list', 'goods_order_thumbnail'])) return json_error('参数有误');
                $res = GoodsModel::where('goods_id', $goods_id)->update([$type => '']);
                if ($res) {
                    if (($goods[$type])) {
                        $this->deleteImg($goods[$type]);
                    }
                    return success('成功');
                }
                return error('失败');
            }
            if ($id > 0) {
                $img = GoodsImgLogic::getOne($id);
                if (empty($img)) return error('参数有误');
                if ($img['goods_id'] != $goods_id) return error('参数有误');
                if ($img['img_src']) {
                    $this->deleteImg($img['img_src']);
                }
                $res = GoodsImgModel::where('img_id', $id)->delete();
                if ($res) {
                    if ($img['img_src']) {
                        $this->deleteImg($img['img_src']);
                    }
                    return success('成功');
                }
                return error('失败');
            }
    }


    /**
     * @param int $goods_id
     * @return array|string
     */
    public  function getGoodsLease(int $goods_id){
        $goods = GoodsLogic::getOne($goods_id, ['goods_name', 'goods_id', 'goods_price', 'goods_official_price', 'goods_purchase_price']);
        if(empty($goods)) return '参数有误';
        $sku = GoodsSkuModel::where('goods_id', $goods_id)->get();
        $sku = ob_to_array($sku);
        $attr_vals = GoodsLogic::getAttrValToTypeByGoodsId($goods_id);
        foreach ($sku as $k => $v) {
            $sku[$k]['sku_str'] = '';
            if ($v['sku']) {
                $ar = explode(',', trim($v['sku'], ','));
                $ars = [];
                foreach ($ar as $v) {
                    if (isset($attr_vals[$v])) $ars[] = $attr_vals[$v];
                }
            }
            $sku[$k]['sku_str'] = join(' | ', $ars);
        }

        $channel_cate_goods=ChannelCateGoodsModel::where([['cha_id',1],['goods_id',$goods_id]])->select('cate_id')->first();
        $channel_cate_goods=ob_to_array($channel_cate_goods);
        $buyMoney=0;
        if($channel_cate_goods){
            $buyMoney=$this->buyMoney($channel_cate_goods['cate_id'],$goods['goods_official_price'],$goods['goods_price']);
        }

        return ['sku' => $sku, 'goods' => $goods,'buyMoney'=>$buyMoney];
    }


    //买断金
    public function buyMoney($cate_id,$goods_official_price,$goods_price){
        $money=0;
        if (in_array($cate_id, [286])) {
            $money = number_deal($goods_official_price * 1.1 - $goods_price, 2);
            $money= abs($money);
        } elseif (in_array($cate_id, [287, 298, 299])) {
            //298苹果电脑 299联想电脑
            $money = number_deal($goods_official_price-$goods_price, 2);
            $money = abs($money);
        } else {
            $money = 0;
        }
        return $money;
    }

    /** 租期设置
     * @param array $para
     * @return array
     * @throws \Exception
     */
    public  function goodsLeaseSet(array $para){
        $goods_id=isset($para['goods_id'])?$para['goods_id']:0;
        $sku=isset($para['sku'])?$para['sku']:0;
        $rent_price=isset($para['rent_price'])?$para['rent_price']:0;
        $deposit_price=isset($para['deposit_price'])?$para['deposit_price']:0;
        $buyout_price=isset($para['buyout_price'])?$para['buyout_price']:0;
        $term_num=isset($para['term_num'])?$para['term_num']:0;
        $price=isset($para['price'])?$para['price']:0;
        $day_num=isset($para['day_num'])?$para['day_num']:0;


        $goods = GoodsLogic::isOne($goods_id);
        if (empty($goods)) return error('参数有误');
        if ($sku > 0) {
            $num = GoodsSkuModel::where([['goods_id', $goods_id], ['id', $sku]])->count();
            if (empty($num)) return error('商品的sku选择有误');
        }

        if ($rent_price <= 1) return error('请设置总租金');
        if ($deposit_price <= 1) return error('请设置押金');
        if ($buyout_price < 0) $buyout_price = 0;
        if ($term_num < 1) return error('请设置租期期数');

        $num = GoodsLeaseModel::where([['goods_id', $goods_id], ['goods_sku_id', $sku], ['term_num', $term_num]])->count();
        if ($num > 0) return error('该商品该规格的租期数已经存在');

        if (empty($price) || empty($day_num)) return error('请设置租期');
        if (count($price) != count($day_num)) return error('租期天数与租金不对等');
        if ($term_num != count($price)) return error('租期期数与租期总数不相等');
        $price_ar = [];
        foreach ($price as $v) {
            if ((float)$v < 0) return error('每期的租金不能小于0');
            $price_ar[] = number_deal($v);
        }
        $total_price = array_sum($price_ar);

        if ($total_price > $rent_price) return error('所有租期的租金和不能大于总租金');
        if (($rent_price - $total_price) > 0.5) return error('总租金与所有租期的租金总和的差必须在0.5之内');
        $day_num_ar = [];
        foreach ($day_num as $v) {
            $v = (int)$v;
            if ($v < 1) return error('每期的天数最小不能小于1');
            $day_num_ar[] = $v;
        }

        $data = [
            'goods_id' => $goods_id,
            'term_num' => $term_num,
            'rent_price' => $rent_price,
            'deposit_price' => $deposit_price,
            'buyout_price' => $buyout_price,
            'goods_sku_id' => $sku
        ];
        DB::beginTransaction();
        try {
            $id = GoodsLeaseModel::insertGetId($data);
            if (empty($id)) throw new \Exception('设置失败');
            $data = [];
            foreach ($price_ar as $k => $v) {
                $data[] = ['price' => $v, 'day_num' => $day_num_ar[$k], 'goods_lease_id' => $id];
            }
            $res = GoodsLeaseTermModel::insert($data);
            if (empty($res)) throw new \Exception('设置失败');
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return error($e->getMessage());
        }
        return success('设置成功');

    }

    public static function goodsLeaseEdit(array $para){
        $goods_id=isset($para['goods_id'])?$para['goods_id']:0;
        $sku=isset($para['sku'])?$para['sku']:0;
        $rent_price=isset($para['rent_price'])?$para['rent_price']:0;
        $deposit_price=isset($para['deposit_price'])?$para['deposit_price']:0;
        $buyout_price=isset($para['buyout_price'])?$para['buyout_price']:0;
        $term_num=isset($para['term_num'])?$para['term_num']:0;
        $price=isset($para['price'])?$para['price']:0;
        $day_num=isset($para['day_num'])?$para['day_num']:0;
        $id=isset($para['id'])?$para['id']:0;

        $goods_lease =GoodsLeaseModel::where('id', $id)->first();
        $goods_lease = ob_to_array($goods_lease);
        if (empty($goods_lease)) return error('参数有误');
        if ($goods_id != $goods_lease['goods_id']) return error('参数错误');
        $goods = GoodsLogic::isOne($goods_id);
        if (empty($goods)) return error('参数有误');

        if ($sku) {
            $num = GoodsSkuModel::where([['goods_id', $goods_id], ['id', $sku]])->count();
            if (empty($num)) return error('商品的sku选择有误');
        }


        if ($rent_price <= 1) return error('请设置总租金');
        if ($deposit_price <= 1) return error('请设置押金');
        if ($buyout_price < 0) $buyout_price = 0;
        if ($term_num < 1) return error('请设置租期期数');

        if (empty($price) || empty($day_num)) return error('请设置租期');
        if (count($price) != count($day_num)) return error('租期天数与租金不对等');
        if ($term_num != count($price)) return error('租期期数与租期总数不相等');
        $price_ar = [];
        foreach ($price as $v) {
            if ((float)$v < 0) return error('每期的租金不能小于0');
            $price_ar[] = number_deal($v);
        }
        $total_price = array_sum($price_ar);


        if ($total_price > $rent_price) return error('所有期的租金和不能大于总租金');
        if (($rent_price - $total_price) > 0.5) return error('总租金与所有期的租金和的差必须在0.5内');
        $day_num_ar = [];
        foreach ($day_num as $v) {
            $v = (int)$v;
            if ($v < 1) return error('每期的天数最小不能小于1');
            $day_num_ar[] = $v;
        }

        $data = [
            'goods_id' => $goods_id,
            'term_num' => $term_num,
            'rent_price' => $rent_price,
            'deposit_price' => $deposit_price,
            'buyout_price' => $buyout_price,
            'goods_sku_id' => $sku
        ];


        $term = GoodsLeaseTermModel::where('goods_lease_id', $id)->select('id')->get();
        $term = ob_to_array($term);
        $term_id_ar = array_column($term, 'id') ?: [];
        $term_num = count($term_id_ar);

        DB::beginTransaction();
        try {
            $res = GoodsLeaseModel::where('id', $id)->update($data);
            $add_data = [];
            foreach ($price_ar as $k => $v) {
                $data = ['price' => $v, 'day_num' => $day_num_ar[$k], 'goods_lease_id' => $id];
                if (($k + 1) <= $term_num) {
                    GoodsLeaseTermModel::where('id', $term_id_ar[$k])->update($data);
                } else {
                    $add_data[] = $data;
                }
                if (isset($term_id_ar[$k])) unset($term_id_ar[$k]);
            }
            //比原数据多的添加
            if ($add_data) {
                $res = GoodsLeaseTermModel::insert($add_data);
                if (empty($res)) throw new \Exception('设置失败');
            }
            //比新数据多出的删除
            if ($term_id_ar) {
                $res =  GoodsLeaseTermModel::whereIn('id', $term_id_ar)->delete();
                if (empty($res)) throw new \Exception('设置失败');
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return error($e->getMessage());
        }
        return success('编辑成功');
    }

    /**
     * @param int $id
     * @return array|string
     */
    public  function getGoodsLeaseById(int $id){
        $data = GoodsLeaseLogic::getOne($id);
        if (empty($data)) return '参数错误';
        $goods = GoodsLogic::getOne($data['goods_id'], ['goods_name', 'goods_id']);
        if (empty($goods))return '参数错误';
        $sku = GoodsSkuLogic::getListByGoodsId($data['goods_id']);
        $attr_vals = GoodsLogic::getAttrValToTypeByGoodsId($data['goods_id']);
        foreach ($sku as $k => $v) {
            $sku[$k]['sku_str'] = '';
            if ($v['sku']) {
                $ar = explode(',', trim($v['sku'], ','));
                $ars = [];
                foreach ($ar as $v) {
                    if (isset($attr_vals[$v])) $ars[] = $attr_vals[$v];
                }
            }
            $sku[$k]['sku_str'] = join(' | ', $ars);
        }

        $term = GoodsLeaseTermLogic::getListByGoodsLeaseId($id);
          return  [
                'info' => $data,
                'sku' => $sku,
                'goods' => $goods,
                'term' => $term
            ];
    }

    /**
     * @param array $para
     * @return array
     */
    public  function goodsAttrAdd(array $para){
        $goods_id = isset($para['goods_id'])?$para['goods_id']:0;
        $name = isset($para['name'])?$para['name']:'';
        $val = isset($para['val'])?$para['val']:'';
        $res = GoodsLogic::isOne($goods_id);
        if (empty($res)) return error('参数有误');
        $data = [];
        if (empty($name) || empty($val)) return error('请设置商品规格参数');
        if (count($name) != count($val)) return error('规格名与规格值不对等');
        foreach ($name as $k => $v) {
            if ($v) {
                if (empty($val[$k])) return error('规格参数对应的规格值不能为空');
                $data[$k]['attr_spec_name'] = trim($v);
                $data[$k]['attr_spec_val'] = trim($val[$k]);
                $data[$k]['goods_id'] = $goods_id;
            }
        }
        if (empty($data)) return error('请正确设置商品规格');
        $res = AttrSpecModel::insert($data);
        if (!$res) return error('添加失败');

        return success('添加成功');
    }

    /**
     * @param int $goods_id
     * @return array|string
     */
    public  function getGoodsAttr(int $goods_id){
        $goods = GoodsLogic::getOne($goods_id, ['goods_name', 'goods_id']);
        if(empty($goods)) return '参数有误';
        $attr = AttrSpecModel::where('goods_id', $goods_id)->get();
        $attr = ob_to_array($attr);

        return [
            'attr' => $attr,
            'goods' => $goods
        ];
    }

    //规格参数删除
    public static function goodsAttrDelete(int $id)
    {
        $attr = AttrSpecModel::where('id', $id)->first();
        if (empty($attr)) return error('参数有误');
        $attr = ob_to_array($attr);
        $goods = GoodsLogic::getOne($attr['goods_id']);
        if (empty($goods)) return error('参数有误');
        if ($goods['is_putaway'] == 3) return error('该商品已经上线无法删除其规格参数');

        $res = AttrSpecModel::where('id', $id)->delete();
        if (!$res) return error('删除失败');

        return success('删除成功');
    }

    /** 规格参数编辑
     * @param array $para
     * @return array
     */
    public   function goodsAttrEdit(array $para){
        $id = isset($para['id'])?$para['id']:0;
        $name = isset($para['name'])?$para['name']:'';
        $zhi = isset($para['zhi'])?$para['zhi']:'';
        $attr = AttrSpecModel::where('id', $id)->first();
        $attr = ob_to_array($attr);
        if (empty($attr)) return error('参数有误');
        if (empty($name)) return error('规格名不能为空');
        if (empty($zhi)) return error('规格值不能为空');


        $goods = GoodsLogic::getOne($attr['goods_id'], ['goods_id', 'is_putaway']);
        if (empty($goods)) return error('参数有误');
        if ($goods['is_putaway'] == 3) return error('该商品已经上线无法编辑其规格参数');

        $res =  AttrSpecModel::where('id', $id)->update(['attr_spec_name' => $name, 'attr_spec_val' => $zhi]);
        if (!$res) return error('编辑失败');

        return success('编辑成功');
    }

    /** 添加sku
     * @param array $para
     * @return array
     * @throws \Exception
     */
    public  function skuAdd(array $para){
        $goods_id = isset($para['goods_id'])?$para['goods_id']:0;
        $id = isset($para['id'])?$para['id']:0;
        $zhi = isset($para['zhi'])?$para['zhi']:[];
        $newattr = isset($para['newattr'])?$para['newattr']:'';

        $goods = GoodsLogic::getOne($goods_id, ['goods_id']);
        if (empty($goods)) return error('该商品不存在');

        if ($id == 0) { //添加新属性
            if (empty($newattr)) return error('请填写新的属性名');

            $res = AttrTypeModel::where([['goods_id', $goods_id], ['attr_type', $newattr]])->first();
            if ($res) return error('该属性已经存在');

            $da = [];
            foreach ($zhi as $v) {
                if ($v) $da[] = $v;
            }
            $da = array_unique($da);
            if (empty($da)) return error('请填写属性值');
            DB::beginTransaction();
            try {
                $attr_id = AttrTypeModel::insertGetId(['goods_id' => $goods_id, 'attr_type' => $newattr]);
                if (empty($attr_id)) throw new \Exception('添加失败');
                $attr_val_id=0;
                foreach ($da as $k=>$v) {
                    $res =  AttrValModel::insertGetId(['goods_id' => $goods_id, 'attr_id' => $attr_id, 'attr_name' => $v]);
                    if($k==0)$attr_val_id=$res;
                    if (empty($res)) throw new \Exception('添加失败');
                }
                $sku=GoodsSkuModel::where('goods_id',$goods_id)->select('sku','id')->get();
                $sku=ob_to_array($sku);
                if($sku && is_array($sku)){
                    foreach($sku as $v){
                        $sku_ar=explode(',',trim($v['sku']));
                        array_push($sku_ar,$attr_val_id);
                        sort($sku_ar);
                        $res=GoodsSkuModel::where('id',$v['id'])->update(['sku'=>trim(join(',',$sku_ar),',')]);
                        if (empty($res)) throw new \Exception('添加失败');
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return error($e->getMessage());
            }
            return success('添加成功');
        }


        $attr_type =  AttrTypeModel::where([['goods_id', $goods_id], ['attr_id', $id]])->first();
        if (empty($attr_type)) return error('参数有误');
        $attr_val = AttrValModel::where([['goods_id', $goods_id], ['attr_id', $id]])->select('attr_name')->get();
        $attr_val = ob_to_array($attr_val);
        $attr_name = $attr_val ? array_column($attr_val, 'attr_name') : [];
        if (empty($zhi) || !is_array($zhi)) return error('请填写属性值');
        $da = [];
        $p = 0;
        foreach ($zhi as $v) {
            if (in_array($v, $attr_name)) $p = 1;
            if ($v && !in_array($v, $attr_name)) $da[] = $v;
        }
        if (empty($da) && $p == 0) return error('请填写属性值');
        if (empty($da) && $p == 1) return error('属性值已经存在');
        $da = array_unique($da);

        DB::beginTransaction();
        try {
            $data = [];
            foreach ($da as $v) {
                $data[] = [
                    'attr_name' => $v,
                    'attr_id' => $id,
                    'goods_id' => $goods_id
                ];
            }
            $re =  AttrValModel::insert($data);
            if (empty($re)) throw new \Exception('添加失败');
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return error($e->getMessage());
        }
        return success('添加成功');
    }

    /**
     * @param int $goods_id
     * @return array|string
     */
    public  function getSkuByGoodsId(int $goods_id){
        $goods = GoodsLogic::getOne($goods_id, ['goods_name', 'goods_id']);
        if (empty($goods)) return '参数错误';
        $attr_type = AttrTypeModel::where("goods_id", $goods_id)->get();
        $attr_type = ob_to_array($attr_type);
        if ($attr_type) {
            $attr_ids = array_column($attr_type, 'attr_id') ?: [0];
            $attr_val =  AttrValModel::where('goods_id', $goods_id)->whereIn('attr_id', $attr_ids)->get();
            $attr_val = ob_to_array($attr_val);
            $attr_vals = [];
            foreach ($attr_val as $v) {
                $attr_vals[$v['attr_id']][] = $v;
            }
            foreach ($attr_type as $k => $v) {
                $attr_type[$k]['zhi'] = $attr_vals[$v['attr_id']] ?? [];
            }
        }

        $url = config('sys.img_url') . '/';
        $data = [
            'sku' => $attr_type,
            'url' => $url,
            'goods' => $goods
        ];
        return $data;
    }

    /** 修改属性名称
     * @param array $para
     * @return array
     */
    public  function ajaxEditAttrType(array $para){
        $id = isset($para['id'])?$para['id']:0;
        $goods_id = isset($para['goods_id'])?$para['goods_id']:0;
        $attr_type = isset($para['attr_type'])?$para['attr_type']:'';
        if(empty($attr_type)) return error('属性名不能为空');


        $res =  AttrTypeModel::where([['attr_id', $id], ['goods_id', $goods_id]])->first();
        $res || die(json_error('参数有误'));
        $res =  AttrTypeModel::whereRaw("goods_id=" . $goods_id . " and attr_type=? and attr_id<>" . $id, [$attr_type])->first();
        $res = ob_to_array($res);
        if($res) return error('该属性已经存在');
        $res =  AttrTypeModel::where('attr_id', $id)->update(['attr_type' => $attr_type]);
        if(empty($res)) return error('修改失败');
        return success('修改成功');
    }

    /**删除属性 同时要删除对应的属性值，sku,租期
     * @param int $attr_id
     * @return array
     * @throws \Exception
     */
    public  function ajaxDelAttrType(int $attr_id){
        $attr_type = AttrTypeModel::where("attr_id", $attr_id)->first();
        if (empty($attr_type)) return error('参数有误');
        $attr_type = ob_to_array($attr_type);
        $goods_id = $attr_type['goods_id'];
        DB::beginTransaction();
        try {
            $attr_val =  AttrValModel::where('attr_id', $attr_id)->select('attr_img', 'id')->get();
            $attr_val = ob_to_array($attr_val);
            $goods_lease_id_ar = GoodsLeaseModel::where("goods_id", $goods_id)->pluck("id");
            $goods_lease_id_ar = ob_to_array($goods_lease_id_ar);
            $res = AttrTypeModel::where('attr_id', $attr_id)->delete();
            if (empty($res)) throw new \Exception('删除失败');

             GoodsSkuModel::where('goods_id', $goods_id)->delete();
            if ($goods_lease_id_ar) {
                $res =  GoodsLeaseModel::where("goods_id", $goods_id)->delete();
                if (empty($res)) throw new \Exception('删除失败');
                GoodsLeaseTermModel::whereIn('goods_lease_id', $goods_lease_id_ar)->delete();
            }
            if ($attr_val) {
                $id_ar = array_column($attr_val, 'id');
                $res =  AttrValModel::where('attr_id', $attr_id)->delete();
                if (empty($res)) throw new \Exception('删除失败');
                foreach ($attr_val as $v) {
                    if ($v['attr_img']) $this->deleteImg($v['attr_img']);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return error($e->getMessage());
        }

        return success('删除成功');
    }

    /** 修改 attr_val  销售属性值
     * @param array $para
     * @return array
     */
    public  function ajaxEditAttrVal(array $para){
        $id = isset($para['id'])?$para['id']:0;
        $attr_id = isset($para['attr_id'])?$para['attr_id']:0;
        $attr_name = isset($para['attr_name'])?$para['attr_name']:'';

        if(empty($attr_name)) return error('属性值不能为空');
        $res =  AttrTypeModel::where('attr_id', $attr_id)->first();
        if(empty($res)) return error('参数有误');
        $res = AttrValModel::whereRaw("attr_id=" . $attr_id . " and attr_name=? and id<>" . $id, [$attr_name])->first();
        if($res) return error('该属性下的属性值已经存在');
        $res = AttrValModel::where('id', $id)->update(['attr_name' => $attr_name]);
        if(empty($res)) return error('修改失败');
        return success('修改成功');
    }

    /** 删除属性值
     * @param int $id
     * @return array
     * @throws \Exception
     */
    public  function ajaxDelAttrVal(int $id){
        $attr_val = AttrValModel::where('id', $id)->select('id', 'attr_img', 'goods_id')->first();
        $attr_val = ob_to_array($attr_val);
        if(empty($attr_val)) return error('该属性值不存在');
        $goods_id = (int)$attr_val['goods_id'];
        $sku = GoodsSkuModel::where('goods_id', $goods_id)->select('sku', 'id')->get();
        $sku = ob_to_array($sku);

        DB::beginTransaction();
        try {
            if ($sku) {
                $delid_ar = [];
                foreach ($sku as $k => $v) {
                    if ($v['sku']) {
                        $ar = explode(',', $v['sku']);
                        if (in_array($id, $ar)) $delid_ar[] = $v['id'];
                    }
                }
                if ($delid_ar) {
                    $res = GoodsSkuModel::whereIn('id', $delid_ar)->delete();
                    if (empty($res)) throw new \Exception('删除失败1');
                    $ar = GoodsLeaseModel::whereIn('goods_sku_id', $delid_ar)->pluck('id');
                    $ar = ob_to_array($ar);
                    if ($ar) {
                         GoodsLeaseTermModel::whereIn('goods_lease_id', $ar)->delete();
                        $res = GoodsLeaseModel::whereIn('id', $ar)->delete();
                        if (empty($res)) throw new \Exception('删除失败2');
                    }
                }
            }
            $re = AttrValModel::where('id', $id)->delete();
            if (empty($re)) throw new \Exception('删除失败3');
            if ($attr_val['attr_img']) $this->deleteImg($attr_val['attr_img']);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return error($e->getMessage());
        }

        return success('删除成功');
    }

    /** 属性图片上传处理
     * @param Request $request
     * @param int $id
     * @return array
     */
    public  function ajaxUploadAttrImg(Request $request,int $id){
        $attr_val = AttrValModel::where('id', $id)->select('id', 'attr_img')->first();
        $attr_val = ob_to_array($attr_val);
        if (empty($attr_val)) return error('参数不正确');
        $data = $this->uploadImg($request, 'img', 'goods_attr');
        if ($data['status'] == 0) {
            return error($data['data']);
        }

        $res = AttrValModel::where('id', $id)->update(['attr_img' => $data['data']]);
        if (empty($res)) {
            $this->deleteImg($data['data']);
            return error('上传失败');
        }

        if ($attr_val['attr_img']) {
            $this->deleteImg($attr_val['attr_img']);
        }
        $url = config('sys.img_url') . '/' . $data['data'];
        return success('上传成功', ['img' => $url]);
    }

    /**
     * @param int $id
     * @return array
     */
    public  function ajaxDelAttrImg(int $id){
        $id = (int)request('id');
        $da = AttrValModel::where('id', $id)->select('id', 'attr_img')->first();
        $da = ob_to_array($da);
        if(empty($da)) return error('该属性值不存在');
        if(empty($da['attr_img'])) return error('该数据还未上传图片');

        $re = AttrValModel::where('id', $id)->update(['attr_img' => '']);
        if(empty($re)) return error('删除失败');
        $this->deleteImg($da['attr_img']);
        return success('删除成功');
    }

    /**给商品设置一组sku
     * @param array $para
     * @return array
     */
    public  function ajaxSetGoodsSku(array $para){
        $goods_id =  isset($para['goods_id'])?$para['goods_id']:0;
        $sku = isset($para['sku'])?$para['sku']:[];
        $goods_price = isset($para['goods_price'])?$para['goods_price']:0;
        $goods_official_price = isset($para['goods_official_price'])?$para['goods_official_price']:0;
        $goods_purchase_price = isset($para['goods_purchase_price'])?$para['goods_purchase_price']:0;

        $goods = GoodsLogic::getOne($goods_id, ['goods_id']);
        if(empty($goods)) return error('商品不存在');
        $attr_id_ar = AttrTypeModel::where('goods_id', $goods_id)->pluck('attr_id');
        $attr_id_ar = ob_to_array($attr_id_ar);
        if(empty($attr_id_ar))  return error('该商品还无属性，请先添加');
        if(empty($sku) || !is_array($sku))  return error('请选择商品属性');
        $sku = array_filter($sku, function ($v) {
            return (int)$v;
        });
        if(empty($sku)) return error('请选择商品属性');
        if(count($sku) != count($attr_id_ar)) return error('选择的属性不全');
        $attr_id_ar1 = AttrValModel::where('goods_id', $goods_id)->whereIn('id', $sku)->pluck('attr_id');
        $attr_id_ar1 = ob_to_array($attr_id_ar1);
        if(empty($attr_id_ar1))  return error('属性选择有误');
        $res_ar = array_diff($attr_id_ar, $attr_id_ar1);
        if($res_ar)  return error('属性选择有误');


        sort($sku);
        $sku = join(',', $sku);
        $res = GoodsSkuModel::whereRaw('goods_id=' . $goods_id . ' and sku=? ', [$sku])->first();
        $res = ob_to_array($res);
        if($res) return error('该组属性已经设置过');
        if (empty($goods_price)) return error('请填写商品sku总价');
        if ($goods_price < 0) return error('请填写正确的商品sku总价');
        if (empty($goods_official_price)) return error('请填写商品sku官方价');
        if ($goods_official_price < 0) return error('请填写正确的商品sku官方价');
        if (empty($goods_purchase_price)) return error('请填写商品sku进货价');
        if ($goods_purchase_price < 0) return error('请填写正确的商品sku进货价');
        if ($goods_price < $goods_purchase_price || $goods_official_price < $goods_purchase_price) return error('商品总价或官方价不能低于进货价');


        $data = [
            'sku' => $sku,
            'goods_price' => number_deal($goods_price, 2),
            'goods_purchase_price' => number_deal($goods_purchase_price, 2),
            'goods_official_price' => number_deal($goods_official_price, 2),
            'goods_id' => $goods_id,
        ];
        $res = GoodsSkuModel::insert($data);
        if(empty($res)) return error('设置失败');

        return success('设置成功');
    }

    /** 编辑商品sku
     * @param array $para
     * @return array
     */
    public  function goodsSkuEdit(array $para){
        $goods_id =  isset($para['goods_id'])?$para['goods_id']:0;
        $sku = isset($para['sku'])?$para['sku']:[];
        $goods_price = isset($para['goods_price'])?$para['goods_price']:0;
        $goods_official_price = isset($para['goods_official_price'])?$para['goods_official_price']:0;
        $goods_purchase_price = isset($para['goods_purchase_price'])?$para['goods_purchase_price']:0;
        $id =  isset($para['id'])?$para['id']:0;

        $res = GoodsSkuLogic::getCountById($id);
        if(empty($res)) return error('参数有误');
        $goods = GoodsLogic::getOne($goods_id, ['goods_id']);
        if(empty($goods)) return error('商品不存在');


        $attr_id_ar = AttrTypeLogic::pluck('attr_id', null, [['goods_id', $goods_id]]);
        if (empty($attr_id_ar)) return error('该商品还无属性，请先添加');
        if (empty($sku) || !is_array($sku)) return error('请选择商品属性1');
        $sku = array_filter($sku, function ($v) {
            return (int)$v;
        });

        if (empty($sku)) return error('请选择商品属性');
        if (count($sku) != count($attr_id_ar))  return error('选择的属性不全');
        $attr_id_ar1 =  AttrValModel::where('goods_id', $goods_id)->whereIn('id', $sku)->pluck('attr_id');
        $attr_id_ar1 = ob_to_array($attr_id_ar1);
        if (empty($attr_id_ar1))  return error('属性选择有误');
        $res_ar = array_diff($attr_id_ar, $attr_id_ar1);
        if ($res_ar)  return error('属性选择有误');

        sort($sku);
        $sku = join(',', $sku);
        $res = GoodsSkuModel::where([['goods_id', $goods_id], ['sku', $sku], ['id', '<>', $id]])->count();
        if($res) return error('该组属性已经设置过');
        if (empty($goods_purchase_price))  return error('请填写商品sku进货价');
        if ($goods_purchase_price < 0) return error('请填写正确的商品sku进货价');
        if (empty($goods_official_price)) return error('请填写商品sku官方价');
        if ($goods_official_price < 0) return error('请填写正确的商品sku官方价');
        if (empty($goods_price)) return error('请填写商品sku总价');
        if ($goods_price < 0) return error('请填写正确的商品sku总价');
        if ($goods_price < $goods_purchase_price || $goods_official_price < $goods_purchase_price) return error('商品总价或官方价不能低于进货价');


        $data = [
            'sku' => $sku,
            'goods_price' => number_deal($goods_price, 2),
            'goods_purchase_price' => number_deal($goods_purchase_price, 2),
            'goods_official_price' => number_deal($goods_official_price, 2),
            'goods_id' => $goods_id,
        ];
        $res =  GoodsSkuModel::where('id', $id)->update($data);
        if(empty($res)) return error('编辑失败');
        return success('编辑成功');
    }


    /**
     * @param int $id
     * @return array
     */
    public  function getGoodsSkuById(int $id){
        $sku = GoodsSkuModel::where('id', $id)->first();
        $sku = ob_to_array($sku);
        if (empty($sku))  return error('参数有误');
        $goods_id = $sku['goods_id'];
        $goods = GoodsLogic::getOne($goods_id, ['goods_id', 'goods_name']);
        if (empty($goods)) {
            return error('参数有误');
        }

        $attr_type = AttrTypeLogic::getListByGoodsId($goods_id, ['attr_id', 'goods_id', 'attr_type']);
        $attr_ids = array_column($attr_type, 'attr_id') ?: [0];
        $attr_val = AttrValLogic::getListByAttrIds($attr_ids);
        $attr_vals = [];
        foreach ($attr_val as $v) {
            $attr_vals[$v['attr_id']][] = $v;
        }
        foreach ($attr_type as $k => $v) {
            $attr_type[$k]['zhi'] = $attr_vals[$v['attr_id']] ?: [];
        }

        $sku['sku_ar'] = explode(',', trim($sku['sku'], ','));
        $data = [
            'attr_type' => $attr_type,
            'goods_id' => $goods_id,
            'sku' => $sku
        ];
        return $data;
    }

    public  function getGoodsList(array $para){
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $is_putaway = isset($para['is_putaway'])?$para['is_putaway']:-1;
        $brand_id = isset($para['brand_id'])?$para['brand_id']:1;
        $cha_id = isset($para['cha_id'])?$para['cha_id']:0;
        $goods_name = isset($para['goods_name'])?$para['goods_name']:'';
        $goods_id = isset($para['goods_id'])?$para['goods_id']:0;
        $start_time = isset($para['start_time'])?$para['start_time']:'';
        $end_time = isset($para['end_time'])?$para['end_time']:'';
        $type = isset($para['type'])?$para['type']:100;


        $where = $searchWhere = [];
        if ($type == 2 || $type == 3 || $type == 4) {
            $searchWhere[] = ['goods.is_putaway', $type];
        }

        if ($brand_id > 0) {
            $where['brand_id'] = $brand_id;
            $searchWhere[] = ['goods.brand_id', $brand_id];
        }
        if ($cha_id > 0) {
            $where['cha_id'] = $cha_id;
            $searchWhere[] = ['c.cha_id', $cha_id];
        }
        if ($goods_id > 0) {
            $where['goods_id'] = $goods_id;
            $searchWhere[] = ['goods.goods_id', $goods_id];
        }
        if ($goods_name) {
            $where['goods_name'] = $goods_name;
            $searchWhere[] = ['goods.goods_name', 'like', $goods_name . '%'];
        }
        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }
        if ($is_putaway != -1) {
            $where['is_putaway'] = $is_putaway;
            $searchWhere[] = ['goods.is_putaway', $is_putaway];
        }
        if ($start_time) {
            $where['start_time'] = $start_time;
            $searchWhere[] = ['goods.create_time', '>', strtotime($start_time)];
        }
        if ($end_time) {
            $where['end_time'] = $start_time;
            $searchWhere[] = ['goods.create_time', '<', strtotime($end_time)];
        }


        $fields = ['goods.goods_img_list', 'goods.goods_order_thumbnail', 'goods.goods_id', 'goods.goods_name', 'goods.is_putaway',
            'goods.keyword', 'goods.goods_price', 'goods.goods_official_price', 'goods.goods_tenancy_term', 'goods.create_time', 'goods.is_delete'];
        $model = GoodsModel::select($fields)->where($searchWhere)->orderBy('goods.goods_id','desc');
        if ($type == 1) {
            $model->whereIn('goods.is_putaway', [1, 5]);
        }
        if ($cha_id > 0) {
            $model->join('channel_cate_goods as c', 'c.goods_id', '=', 'goods.goods_id');
        }
        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);
        $is_putaway=config('sys.goods_status');
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['goods_status'] = isset($is_putaway[$v['is_putaway']]) ? $is_putaway[$v['is_putaway']] : '未知状态';
            $data['data'][$k]['is_set_spec']=$this->is_set_spec($v['goods_id']);
            $data['data'][$k]['is_set_attrType']=$this->is_set_attrType($v['goods_id']);
            $data['data'][$k]['is_set_GoodsSku']=$this->is_set_GoodsSku($v['goods_id']);
            $data['data'][$k]['is_set_GoodsLease']=$this->is_set_GoodsLease($v['goods_id']);
            $data['data'][$k]['is_set_GoodsImg']=$this->is_set_GoodsImg($v['goods_id']);
        }

        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
        }
        $data['page_url'] = trim($url, '&');
        $brand =  BrandModel::where([['brand_is_del', 1], ['is_official_auth', 2]])->pluck('brand_name', 'brand_id');
        $channel = ChannelModel::where('cha_status', 2)->pluck('cha_describe', 'cha_id');
        $url=config('sys.img_url').'/';
        $data= ['data' => $data, 'brand' => $brand, 'channel' => $channel, 'where' => $where,'url'=>$url];
        return $data;
    }

    /** 获取设置租金的三个金额
     * @param int $id
     * @return array
     */
    public function getLeaseMoneys(int $id){
        $sku=GoodsSkuModel::where('id',$id)->first();
        $sku=ob_to_array($sku);
        if(empty($sku)){
            return error('参数有误');
        }
        $goods_id=$sku['goods_id'];

        $goods=GoodsModel::where('goods_id',$goods_id)->first();
        $goods=ob_to_array($goods);
        if(empty($goods)){
            return error('参数有误');
        }
        $channel_cate_goods=ChannelCateGoodsModel::where([['cha_id',1],['goods_id',$goods_id]])->select('cate_id')->first();
        $channel_cate_goods=ob_to_array($channel_cate_goods);
        $buyMoney=0;
        if($channel_cate_goods){
            $buyMoney=$this->buyMoney($channel_cate_goods['cate_id'],$sku['goods_official_price'],$sku['goods_price']);
        }

        return success('ok',[
            'rent_price'=>$sku['goods_price'],
            'buyout_price'=>$buyMoney,
            'deposit_price'=>$sku['goods_price'],
        ]);
    }

    /** 判断是否设置过规格
     * @param int $goods_id
     * @return mixed
     */
    public function is_set_spec(int $goods_id){
        $count= AttrSpecModel::where('goods_id',$goods_id)->count();
        return $count;
    }

    /** 判断是否设置过属性
     * @param int $goods_id
     * @return mixed
     */
    public function is_set_attrType(int $goods_id){
        $count= AttrTypeModel::where('goods_id',$goods_id)->count();
        return $count;
    }

    /** 判断是否设置过sku
     * @param int $goods_id
     * @return mixed
     */
    public function is_set_GoodsSku(int $goods_id){
        $count= GoodsSkuModel::where('goods_id',$goods_id)->count();
        return $count;
    }

    /** 判断是否设置过租期
     * @param int $goods_id
     * @return mixed
     */
    public function is_set_GoodsLease(int $goods_id){
        $count= GoodsLeaseModel::where('goods_id',$goods_id)->count();
        return $count;
    }

    /** 判断商品图片是否设置全
     * @param int $goods_id
     * @return mixed
     */
    public function is_set_GoodsImg(int $goods_id){
        $count= GoodsImgModel::where('goods_id',$goods_id)->count();
        if(empty($count)) return false;

        $img=GoodsModel::where('goods_id',$goods_id)->select('goods_img_list','goods_order_thumbnail')->first();
        $img=ob_to_array($img);
        if(empty($img['goods_img_list']) || empty($img['goods_order_thumbnail'])) return false;
        return true;
    }
























}
